package com.example.usermanagement.listen;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.example.usermanagement.enums.ResponseStatus;
import com.example.usermanagement.events.LiuKaApplicationLogEvent;
import com.example.usermanagement.exception.ServerErrorException;
import com.example.usermanagement.liuka.service.FlowPackageUserService;
import com.example.usermanagement.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author yha
 * @ClassName
 * @description:流量消耗监听
 * @date 2024年09月10日
 * @version: 1.0.0
 */
@Slf4j
@Service
public class LiukaListen implements ApplicationListener<LiuKaApplicationLogEvent> {


    private FlowPackageUserService flowPackageUserService;

    @Value("${liuka.url}")
    private String url;

    @Value("${liuka.log-url}")
    private String logUrl;

    private Lock lock = new ReentrantLock(true);

    @Override
    @Async
    public void onApplicationEvent(LiuKaApplicationLogEvent event) {
        log.info("【onLiukaApplication】用户id:{},消耗流量:{}KB",event.getFlowUserId(),event.getFlowSize());
        Map<String,Object> param = new HashMap<>();
        param.put("flowUserId",event.getFlowUserId());
        param.put("flowSize",event.getFlowSize());
        try {

            lock.lock();
            HashMap<String, String> headerMap = new HashMap<>();
            headerMap.put(Header.CONTENT_TYPE.getValue(), ContentType.FORM_URLENCODED.getValue()); // application/x-www-form-urlencoded
            // post 请求默认是 application/json，如果是 application/x-www-form-urlencoded 则需要保证参数在url后

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, Object> stringObjectEntry : param.entrySet()) {
                String key = stringObjectEntry.getKey();
                Object value = stringObjectEntry.getValue();
                sb.append(key).append("=").append(value).append("&");
            }
            String bodyStr = sb.deleteCharAt(sb.length() - 1).toString();

            String postUrl = url + logUrl;
            HttpResponse response = HttpRequest.post(postUrl)
                    // .form(bodyMap) // url 上加参数
                    .body(bodyStr)
                    .addHeaders(headerMap).timeout(20000).execute();

            ResultVO resultVO = JSONObject.parseObject(response.body(),ResultVO.class);

            if (!resultVO.getCode().equals(ResponseStatus.OK.getCode())) {
                throw new ServerErrorException(resultVO.getMsg());
            }

        }catch (Exception e){
            log.error("出现异常:{}",e.getMessage());
        }finally {
            lock.unlock();
        }
    }
}
